<?php

/**
 * 订单处理
 */

/**
 *  订单列表
 * @access  public
 * @param   int         $user_id        用户ID号
 * @param   int         $num            列表最大数量
 * @param   int         $start          列表起始位置
 * @return  array       $order_list     订单列表
 */
function get_user_orders($user_id, $num = 10, $start = 0)
{
    /* 取得订单列表 */
    $arr    = array();
    $sql = "SELECT *, comment,order_id, order_sn,invoice_no, order_status,pay_name, shipping_status, pay_status, add_time, " .
           "(goods_amount + shipping_fee + insure_fee + pay_fee + tax - discount) AS total_fee ".
           " FROM " .$GLOBALS['ecs']->table('order_info') .
           " WHERE user_id = '$user_id' AND join_id=0 ORDER BY add_time DESC";
    $res = $GLOBALS['db']->SelectLimit($sql, $num, $start);
    $i = 0;
    while ($row = $GLOBALS['db']->fetchRow($res)){
        $arr[$i]['orderId']= $row['order_id'];        //订单号
        $arr[$i]['orderSn']= $row['order_sn'];        //订单号
        $arr[$i]['orderStatus']= $row['order_status'];    //订单状态
        $arr[$i]['payStatus']= $row['pay_status'];      //支付状态
        $arr[$i]['totalFee']= $row['total_fee'];       //总金额
        $arr[$i]['time']= date('Y-m-d H:i:s', $row['add_time']);        //订单添加时间
        $i++;
    }
    return $arr;
}

/**
 *  获取订单的详情
 * @access  public
 * @param   int         $order_id       订单ID
 * @param   int         $user_id        用户ID
 * @return   arr        $order          订单所有信息的数组
 */
function get_order_detail($order_id, $user_id = 0)
{
    include_once(ROOT_PATH . 'includes/lib_order.php');

    $order_id = intval($order_id);
    if ($order_id <= 0)
    {
        errorMsg($GLOBALS['_LANG']['invalid_order_id']);

        return false;
    }
    $order = order_info($order_id);

    //检查订单是否属于该用户
    if ($user_id > 0 && $user_id != $order['user_id'])
    {
        errorMsg($GLOBALS['_LANG']['no_priv']);

        return false;
    }

    /* 只有未确认才允许用户修改订单地址 */
    if ($order['order_status'] == OS_UNCONFIRMED)
    {
        $order['allow_update_address'] = 1; //允许修改收货地址
    }
    else
    {
        $order['allow_update_address'] = 0;
    }

    /* 获取订单中实体商品数量 */
    $order['exist_real_goods'] = exist_real_goods($order_id);

    /* 确认时间 支付时间 发货时间 */
    if ($order['confirm_time'] > 0 && ($order['order_status'] == OS_CONFIRMED || $order['order_status'] == OS_SPLITED || $order['order_status'] == OS_SPLITING_PART))
    {
        $order['confirm_time'] = sprintf($GLOBALS['_LANG']['confirm_time'], local_date($GLOBALS['_CFG']['time_format'], $order['confirm_time']));
    }
    else
    {
        $order['confirm_time'] = '';
    }
    if ($order['pay_time'] > 0 && $order['pay_status'] != PS_UNPAYED)
    {
        $order['pay_time'] = sprintf($GLOBALS['_LANG']['pay_time'], local_date($GLOBALS['_CFG']['time_format'], $order['pay_time']));
    }
    else
    {
        $order['pay_time'] = '';
    }
    if ($order['shipping_time'] > 0 && in_array($order['shipping_status'], array(SS_SHIPPED, SS_RECEIVED)))
    {
        $order['shipping_time'] = sprintf($GLOBALS['_LANG']['shipping_time'], local_date($GLOBALS['_CFG']['time_format'], $order['shipping_time']));
    }
    else
    {
        $order['shipping_time'] = '';
    }

    return $order;

}

/**
 * 取消一个用户订单
 *
 * @access  public
 * @param   int         $order_id       订单ID
 * @param   int         $user_id        用户ID
 *
 * @return void
 */
function cancel_order($order_id, $user_id = 0)
{
    /* 查询订单信息，检查状态 */
    $sql = "SELECT user_id, order_id, order_sn, join_id , surplus , integral , bonus_id, order_status, shipping_status, pay_status FROM " .$GLOBALS['ecs']->table('order_info') ." WHERE order_id = '$order_id'";
    $order = $GLOBALS['db']->GetRow($sql);

    if (empty($order))
    {
        errorMsg($GLOBALS['_LANG']['order_exist']);
        return false;
    }

    // 如果用户ID大于0，检查订单是否属于该用户
    if ($user_id > 0 && $order['user_id'] != $user_id)
    {
        errorMsg($GLOBALS['_LANG']['no_priv']);
        return false;
    }

    // 订单状态只能是“未确认”或“已确认”
    if ($order['order_status'] != OS_UNCONFIRMED && $order['order_status'] != OS_CONFIRMED)
    {
        errorMsg($GLOBALS['_LANG']['current_os_not_unconfirmed']);
        return false;
    }

    //订单一旦确认，不允许用户取消
    if ( $order['order_status'] == OS_CONFIRMED)
    {
        errorMsg($GLOBALS['_LANG']['current_os_already_confirmed']);
        return false;
    }

    // 发货状态只能是“未发货”
    if ($order['shipping_status'] != SS_UNSHIPPED)
    {
        errorMsg($GLOBALS['_LANG']['current_ss_not_cancel']);
        return false;
    }

    // 如果付款状态是“已付款”、“付款中”，不允许取消，要取消和商家联系
    if ($order['pay_status'] != PS_UNPAYED)
    {
        errorMsg($GLOBALS['_LANG']['current_ps_not_cancel']);
        return false;
    }

    // 如果为合单订单状态，不允许子单取消订单
    if ($order['join_id'] >0){
        if($order['join_id'] != $order['order_sn']){
            $sql = "UPDATE ".$GLOBALS['ecs']->table('order_info') ." SET order_status = 3 WHERE order_id = '$order_id'";
        }else{
            $sql = "UPDATE ".$GLOBALS['ecs']->table('order_info') ." SET order_status = '".OS_CANCELED."' WHERE join_id = '$order[join_id]'";
        }
    }else{
        $sql = "UPDATE ".$GLOBALS['ecs']->table('order_info') ." SET order_status = '".OS_CANCELED."' WHERE order_id = '$order_id'";
    }

    //将用户订单设置为取消
    if ($GLOBALS['db']->query($sql))
    {
        /* 记录log */
        order_action($order['order_sn'], OS_CANCELED, $order['shipping_status'], PS_UNPAYED,$GLOBALS['_LANG']['buyer_cancel'],'buyer');
        /* 退货用户余额、积分、红包 */
        if ($order['user_id'] > 0 && $order['surplus'] > 0)
        {
            $change_desc = sprintf($GLOBALS['_LANG']['return_surplus_on_cancel'], $order['order_sn']);
            log_account_change($order['user_id'], $order['surplus'], 0, 0, 0, $change_desc);
        }
        
        if ($order['user_id'] > 0 && $order['integral'] > 0)
        {
            $change_desc = sprintf($GLOBALS['_LANG']['return_integral_on_cancel'], $order['order_sn']);
            log_account_change($order['user_id'], 0, 0, 0, $order['integral'], $change_desc);
        }
        if ($order['user_id'] > 0 && $order['bonus_id'] > 0)
        {
            change_user_bonus($order['bonus_id'], $order['order_id'], false);
        }

        /* 如果使用库存，且下订单时减库存，则增加库存 */
        if ($GLOBALS['_CFG']['use_storage'] == '1' && $GLOBALS['_CFG']['stock_dec_time'] == SDT_PLACE)
        {
            change_order_goods_storage($order['order_id'], false, 1);
        }

        /* 修改订单 */
        $arr = array(
            'bonus_id'  => 0,
            'bonus'     => 0,
            'integral'  => 0,
            'integral_money'    => 0,
            'surplus'   => 0
        );
        update_order($order['order_id'], $arr);

        return true;
    }
    else
    {
        errorMsg($GLOBALS['db']->errorMsg());
    }
}

/**
 * 获取用户帐号信息
 *
 * @access  public
 * @param   int       $user_id        用户user_id
 *
 * @return void
 */
function get_profile($user_id)
{
    global $user;
    /* 会员帐号信息 */
    $info  = array();
    $infos = array();
    $sql  = ' SELECT ui.*, u.user_id, u.user_name, u.rank_points, u.pay_points, u.user_money, u.user_rank, u.mobile_phone, u.email, u.is_validated, u.is_mobile_validated ' . 
           ' FROM ' . $GLOBALS['ecs']->table('user_info') . ' AS ui ' . 
           ' LEFT JOIN ' . $GLOBALS['ecs']->table('users') . ' AS u ' . 
                " ON ui.user_id = u.user_id " . 
           " WHERE u.user_id = '$user_id'";

    $infos = $GLOBALS['db']->getRow($sql);
    $infos['user_name'] = addslashes($infos['user_name']);
    $row = $user->get_profile_by_name($infos['user_name']); //获取用户帐号信息
    // $_SESSION['email'] = $row['email'];    //注册SESSION

    /* 会员等级 */
    if ($infos['user_rank'] > 0)
    {
        $sql = "SELECT rank_id, rank_name, discount FROM ".$GLOBALS['ecs']->table('user_rank') .
               " WHERE rank_id = '$infos[user_rank]'";
    }
    else
    {
        $sql = "SELECT rank_id, rank_name, discount, min_points".
               " FROM ".$GLOBALS['ecs']->table('user_rank') .
               " WHERE min_points<= " . intval($infos['rank_points']) . " ORDER BY min_points DESC";
    }

    if ($row = $GLOBALS['db']->getRow($sql))
    {
        $info['rank_name']     = $row['rank_name'];
    }
    else
    {
        $info['rank_name'] = $GLOBALS['_LANG']['undifine_rank'];
    }
    $cur_date = date('Y-m-d H:i:s');

    /* 会员红包 */
    $bonus = array();
    $sql = "SELECT type_name, type_money ".
           "FROM " .$GLOBALS['ecs']->table('bonus_type') . " AS t1, " .$GLOBALS['ecs']->table('user_bonus') . " AS t2 ".
           "WHERE t1.type_id = t2.bonus_type_id AND t2.user_id = '$user_id' AND t1.use_start_date <= '$cur_date' ".
           "AND t1.use_end_date > '$cur_date' AND t2.order_id = 0";
    $bonus = $GLOBALS['db']->getAll($sql);
    if ($bonus)
    {
        for ($i = 0, $count = count($bonus); $i < $count; $i++)
        {
            $bonus[$i]['type_money'] = price_format($bonus[$i]['type_money'], false);
        }
    }

    // $info['head_url']    = $infos['head_url'];          //用户头像
    $info['signature']   = $infos['signature'];         //个性签名
    // $info['user_name']   = $_SESSION['user_name'];      //用户名
    $info['real_name']   = $infos['real_name'];         //真实姓名
    $info['sex']         = isset($infos['sex']) ? $infos['sex'] : 0;   
    $info['birthday']    = isset($infos['birthday']) ? $infos['birthday'] : '';
    $info['mobile_phone']= $infos['mobile_phone'];
    $info['qq']          = $infos['qq'];                
    $info['email']       = $infos['email'];             //email
    $info['school_name'] = $infos['school_name'];       //学校名称
    $info['camp']        = $infos['camp'];              //集训区
    $info['studio']      = $infos['studio'];            //画室名称
    $info['picture_age'] = $infos['picture_age'];       //画龄
    $info['hobby']       = $infos['hobby'];             //兴趣爱好
    
    return $info;
}



?>